<template>
  <div class="vertical_position">
    <a-tree
        :blockNode="true"
        :selectable="false"
        checkable
        show-icon
        :multiple="true"
        :tree-data="positionList"
        v-model:expandedKeys="expandedKeys"
        v-model:checkedKeys="checkedKeys"
        @check="handleCheckChange"
    >
      <template #icon="{ dataRef }">
        <template v-if="dataRef.childType == 'village'">
          <bl-icon type="tree-xiangmu" class="tree-icon"/>
        </template>
        <template v-if="dataRef.childType == 'park'">
          <CuIcon type="org-tingchechang" class="tree-icon"/>
        </template>
        <template v-if="dataRef.childType == 'position'">
          <CuIcon type="org-cheliangdianwei" class="tree-icon"/>
        </template>
      </template>

      <template #title="{ dataRef }">
        <template v-if="dataRef.childType == 'position'">
          <div style="display: inline-block; width: 230px">
            <span>
              <span style="width: 70px; display: inline-block">{{
                  dataRef.title
                }}</span>
              <a
                  @click.stop="chooseUser(dataRef.userList, dataRef.key)"
                  style="margin-left: 10px"
                  v-if="!dataRef.owner_id && dataRef.userList && dataRef.userList.length > 0 && dataRef.space_area * 1 != 0"
              >绑定用户</a
              >
            </span>
            <a
                style="float: right"
                :style="{ color: dataRef.space_area * 1 == 0 ? 'gray' : '' }"
                v-if="dataRef.space_area || dataRef.space_area * 1 == 0"
            >{{ dataRef.space_area }}m²</a
            >
          </div>
        </template>
        <template v-else>
          <span>{{ dataRef.title }}</span>
        </template>
      </template>
    </a-tree>

    <a-modal
        :width="520"
        v-model:visible="userVisible"
        title="选择用户"
        @cancel="handleCancel"
        :footer="null"
        centered
    >
      <section class="content" v-if="currentUserList.length > 0">
        <div class="top_con">
          <span v-if="currentPosition.village_name"
          >项目：{{ currentPosition.village_name }}</span
          >
          <span v-if="currentPosition.park_name"
          >车场：{{ currentPosition.park_name }}</span
          >
          <span v-if="currentPosition.position_name"
          >车位：{{ currentPosition.position_name }}</span
          >
        </div>
        <section>
          <ul class="list">
            <li
                class="item"
                v-for="(item, index) in currentUserList"
                :key="index"
                @click="handleUserChange(item)"
            >
              <div class="left">
                <UsergroupAddOutlined/>
                <div class="name">{{ item.name }}（{{ item.owner_id }}）</div>
              </div>
              <div class="right">
                <PlusCircleOutlined/>
              </div>
            </li>
          </ul>
        </section>
      </section>
    </a-modal>
  </div>
</template>

<script>
import {BlIcon} from "bl-common-vue3";
import {
  InsertRowLeftOutlined,
  CarOutlined,
  PicCenterOutlined,
  UsergroupAddOutlined,
  PlusCircleOutlined,
} from "@ant-design/icons-vue";
import {defineComponent, watch, ref, toRefs, reactive, nextTick} from "vue";
import request from "../../../../common/utils/request";

export default defineComponent({
  props: {
    villageId: {
      type: [String, Number],
      default: 0,
    },
    standardInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  components: {
    InsertRowLeftOutlined,
    CarOutlined,
    PicCenterOutlined,
    "bl-icon": BlIcon,
    UsergroupAddOutlined,
    PlusCircleOutlined,
  },

  setup(props, context) {
    const state = reactive({
      currentUserList: [],
      currentKey: "",
      currentPosition: {},
      userVisible: false,
      expandedKeys: [],
      checkedKeys: [],
      positionList: [],
      allPosition: [],
    });

    const getParkList = (villageId) => {
      state.positionList = [];
      state.allPosition = [];
      state.expandedKeys = [];
      request.get("/org", "/park/list", {villageId}).then((res) => {
        state.positionList.push({
          title: res.result.name,
          key: res.result.villageId,
          children: [],
          isLeaf: false,
          childType: "village",
        });
        state.expandedKeys.push(res.result.villageId);
        nextTick(() => {
          state.expandedKeys = [...state.expandedKeys];
        });
        if (res.result.parkList.length == 0) return;
        res.result.parkList.map((parkItem, parkIndex) => {
          parkItem.children = [];
          state.positionList[0].children.push({
            id: parkItem.id,
            title: parkItem.park_name,
            key: parkItem.village_id + "-" + parkItem.id,
            children: parkItem.children,
            isLeaf: false,
            childType: "park",
          });
          getPositionList(parkItem, parkIndex);
        });
      });
    };

    const getPositionList = (parkItem, parkIndex) => {
      request
          .get("/org", "/park/space/list", {parkId: parkItem.id})
          .then((res) => {
            if (res.result.length == 0) return;
            state.allPosition = [...state.allPosition, ...res.result];
            res.result.map((positionItem) => {
              if (positionItem.userList && positionItem.userList.length == 1) {
                positionItem.hasOwnerId = 0;
                if (!positionItem.owner_id) {
                  positionItem.owner_id = positionItem.userList[0].owner_id;
                  positionItem.hasOwnerId = 1;
                }
                if (!positionItem.user_name) {
                  positionItem.user_name = positionItem.userList[0].name;
                }
              } else {
                positionItem.hasOwnerId = 0;
              }
              state.positionList[0].children[parkIndex].children.push({
                id: positionItem.id,
                user_phone: positionItem.user_phone,
                park_name: parkItem.park_name,
                title: positionItem.space_name,
                key:
                    positionItem.village_id +
                    "-" +
                    positionItem.park_id +
                    "-" +
                    positionItem.id,
                isLeaf: true,
                space_area: positionItem.space_area,
                disableCheckbox:
                    (positionItem.space_area * 1 == 0 &&
                        props.standardInfo.mode == 2) || !positionItem.lease_owner_id,
                userList: positionItem.userList,
                owner_id: positionItem.owner_id,
                hasOwnerId: positionItem.hasOwnerId,
                childType: "position",
              });
            });
          });
    };

    const handleCheckChange = (checkedKeys) => {
      state.checkedKeys = checkedKeys;
    };

    watch(
        () => state.checkedKeys,
        (val) => {
          let parkSpaceList = [];
          state.checkedKeys.map((key_item) => {
            if (typeof key_item == "string" && key_item.split("-").length == 3) {
              let arr = key_item.split("-");
              state.positionList[0].children.map((first_item) => {
                if (
                    first_item.id == arr[1] &&
                    first_item.children &&
                    first_item.children.length > 0
                ) {
                  first_item.children.map((second_item) => {
                    if (second_item.id == arr[2]) {
                      state.allPosition.map((item) => {
                        if (
                            item.village_id + "-" + item.park_id + "-" + item.id ==
                            key_item
                        ) {
                          item.park_name = second_item.park_name;
                          item.owner_id = second_item.owner_id;
                          if (second_item.user_name) {
                            item.user_name = second_item.user_name;
                          }
                          item.hasOwnerId = second_item.hasOwnerId;
                          parkSpaceList.push(item);
                        }
                      });
                    }
                  });
                }
              });
            }
          });
          context.emit("setPosition", {
            parkSpaceList: parkSpaceList,
            village_name: state.positionList[0].title,
          });
        },
        {
          deep: true,
        }
    );

    const handleUserChange = (item) => {
      state.userVisible = false;
      let arr = state.currentKey.split("-");
      state.positionList[0].children.map((first_item) => {
        if (
            first_item.id == arr[1] &&
            first_item.children &&
            first_item.children.length > 0
        ) {
          first_item.children.map((second_item) => {
            if (second_item.id == arr[2]) {
              second_item.hasOwnerId = 1;
              second_item.owner_id = item.owner_id;
              second_item.user_name = item.name;
              second_item.disableCheckbox =
                  (second_item.space_area * 1 == 0 &&
                      props.standardInfo.mode == 2) || !second_item.lease_owner_id;
              if (
                  !second_item.disableCheckbox &&
                  state.checkedKeys.indexOf(state.currentKey) == -1
              ) {
                state.checkedKeys.push(state.currentKey);
              }
            }
          });
        }
      });
    };

    const handleCancel = () => {
      state.userVisible = false;
      state.currentUserList = [];
      state.currentKey = "";
      state.currentPosition = {};
    };

    const chooseUser = (userList, key) => {
      state.currentUserList = userList;
      state.currentKey = key;
      let arr = state.currentKey.split("-");
      state.currentPosition["village_name"] = state.positionList[0].title;
      state.positionList[0].children.map((first_item) => {
        if (
            first_item.id == arr[1] &&
            first_item.children &&
            first_item.children.length > 0
        ) {
          state.currentPosition["park_name"] = first_item.title;
          first_item.children.map((second_item) => {
            if (second_item.id == arr[2]) {
              state.currentPosition["position_name"] = second_item.title;
            }
          });
        }
      });
      state.userVisible = true;
    };

    getParkList(props.villageId);

    return {
      ...toRefs(state),
      handleCheckChange,
      handleUserChange,
      handleCancel,
      chooseUser,
    };
  },
});
</script>

<style lang="less" scoped>
:deep(.ant-modal-body) {
  padding-top: 12px !important;
}

:deep(.ant-tree-node-content-wrapper, .ant-tree-node-content-wrapper-normal) {
  display: flex !important;
}

.vertical_position {
  height: 452px;
  overflow-y: scroll;

  .tree-icon {
    font-size: 16px;
    width: 24px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    vertical-align: middle;
  }
}

.content {
  .top_con {
    display: flex;
    align-items: center;

    span {
      margin-left: 12px;

      &:nth-child(1) {
        margin-left: 0;
      }
    }
  }

  .list {
    border: 1px solid #dddddd;
    padding: 10px;
    border-radius: 8px;
    margin-top: 12px;

    .item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px;
      cursor: pointer;
      border-radius: 6px;

      &:hover {
        background-color: #f7f7f7;
      }

      .left {
        flex: 1;
        display: flex;
        align-items: center;

        .logo {
          width: 32px;
          height: 32px;
          border-radius: 24%;
        }

        .name {
          margin-left: 10px;
          font-size: 14px;
          color: #000;
        }

        .icon {
          font-size: 16px;
          background: #f4f4f4;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }

      .right {
        width: 40px;
        text-align: right;
        font-size: 14px;
      }
    }

    .item2 {
      .right {
        color: #999;
        font-size: 14px;
      }
    }
  }
}
</style>
